package net.whzjkj.gateway.tcpserver.handler;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import net.whzjkj.gateway.core.handler.AbstractChannelInitializer;
import net.whzjkj.gateway.tcpserver.constant.JT808Constant;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 *    ChannelInitializer是默认的initializer，因此需要继承ChannelInitializer类来实现自己的initializer
 * @author: Mr.Hu
 * @create: 2018-11-05 20:09
 **/
@Component
public class MyChannelInitializer extends AbstractChannelInitializer<SocketChannel> {
    @Resource
    private TcpServerHandler tcpServerHandler;
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        // 添加到pipeline中的handler会被串行处理(PS: 类似工业生产中的流水线)
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
        pipeline.addLast("idleStateHandler",
                new IdleStateHandler(30, 0, 0, TimeUnit.MINUTES));
        pipeline.addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer(new byte[]{JT808Constant.PACKAGE_MARKER}),
                Unpooled.copiedBuffer(new byte[]{JT808Constant.PACKAGE_MARKER, JT808Constant.PACKAGE_MARKER})));
        //pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        //pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(tcpServerHandler);
    }
}
